<?php
/**
 * 国内库存（实时库存）
 * (model)
 */

namespace App\Models\Inventory;

use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use Illuminate\Database\Eloquent\Model;
class Timely extends Model
{
    protected $table = 'inventory_cn';

    protected $guarded = [];

    public $timestamps = false;

    const GROUP_BY = 'psku_id';

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    public static function getDownloadData($re){
        foreach ($re as $row){
            $temp = [];
            $temp['psku_code'] = $row->sku->psku_code ?? '';
            $temp['season'] = ProductClassify::$_season[$row->sku->classify->season ?? 3];
            $temp['classify'] = $row->sku->classify->title ?? '';
            $temp['instant'] = $row->instant;
            $temp['transit'] = $row->transit;
            $temp['reserve'] = $row->reserve;
            $temp['psku_cn'] = $row->sku->psku_cn ?? '';
            yield $temp;
        }
    }

    public static function getInstant($pSkuId){
        return self::query()->where('psku_id',$pSkuId)->sum('instant');
    }

    public static function getTransit($pSkuId){
        return self::query()->where('psku_id',$pSkuId)->sum('transit');
    }

    public static function getAreaTransit($pSkuId){
        return self::query()->where('psku_id',$pSkuId)->sum('area_transit');
    }

    public static function getReserve($pSkuId){
        return self::query()->where('psku_id',$pSkuId)->sum('reserve');
    }

    /**
     * 在库
     * @param null $pSkuIds
     * @param null $areaId
     * @return int|mixed
     */
    public static function getClassifyInstant($pSkuIds = null,$areaId = null){
        $query = self::query();
        if ($pSkuIds) $query->whereIn('psku_id',$pSkuIds);
        if ($areaId) $query->where('area_id',$areaId);

        return $query->sum('instant');
    }

    /**
     * 销售站点在途
     * @param null $pSkuIds
     * @param null $areaId
     * @return int|mixed
     */
    public static function getClassifyTransit($pSkuIds = null,$areaId = null){
        $query = self::query();
        if ($pSkuIds) $query->whereIn('psku_id',$pSkuIds);
        if ($areaId) $query->where('area_id',$areaId);

        return $query->sum('area_transit');
    }

}
